package cn.com.gridinfo.sooc.core.expand.callname.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.Log;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.core.expand.callname.adapter.HistoryCallnameAdapter;
import cn.com.gridinfo.sooc.core.expand.callname.bean.ClassInfo;
import cn.com.gridinfo.sooc.core.expand.callname.common.CodeConst;
import cn.com.gridinfo.sooc.core.expand.callname.common.PageConst;
import cn.com.gridinfo.sooc.core.expand.callname.dao.CallNameDao;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;

/**
 * 历史点名界面
 *
 * @author yingchunli
 */
public class HistoryCallNameActivity extends BaseSoocActivity {

    CallNameDao dao;
    LinearLayoutManager linearLayoutManager;//布局管理器
    @InjectView(R.id.list_callnametongji)
    UltimateRecyclerView listHistoryCallname;//列表数据
    HistoryCallnameAdapter adapter;//适配器
    int maxLastPositon;//分页最后位置
    @InjectView(R.id.searchcontent)
    ClearEditText searchcontent;//搜索内容
    @InjectView(R.id.count)
    TextView count;//点名总次数
    @InjectView(R.id.countLayout)
    LinearLayout countLayout;//点名总次数 行
    private final int INTENT_SIGNINFO = 9;//跳转到签到详情界面的常量
    @InjectView(R.id.search_result)
    RelativeLayout searchResult;//搜索结果
    @InjectView(R.id.searchCount_historyCallname)
    TextView searchCount;//搜索数量
    @InjectView(R.id.blank_view)
    RelativeLayout layout;//空白页布局

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.expand_callname_history);
        dao = new CallNameDao(this);
        ButterKnife.inject(this);
        //初始化listView
        linearLayoutManager = new LinearLayoutManager(this);
        listHistoryCallname.setLayoutManager(linearLayoutManager);

        //发送请求，获取列表数据
        PageConst.pageNo = 1;
        PageConst.pageSize = 10;
        dao.getHistoryClass(PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_HISTORY_CALLNEM_FRIST);//获取数据

        //按键完成监听
        searchcontent.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        searchcontent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onClick();
                }
                return false;
            }
        });
        countLayout.setVisibility(View.GONE);//点名总次数不显示
    }

    /**
     * 搜索内容从有到空，需要重新加载列表
     */
    @OnTextChanged(value = {R.id.searchcontent}, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void onAfterTextChanged() {
        if (searchcontent.getText().toString().trim().equals("")) {
            PageConst.pageNo = 1;
            PageConst.pageSize = 10;
            //发送请求  获取列表
            dao.getHistoryClass(PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_HISTORY_CALLNEM_PUSHDOWN);
        }
    }


    /**
     * 无数据时，空白页的处理
     */
    void setBlankView(String search) {
        layout.setVisibility(View.VISIBLE);
        ImageView imageView = (ImageView) findViewById(R.id.blank_icon);
        TextView textView = (TextView) findViewById(R.id.tipBlank);
        if (search.equals("search")) {
            imageView.setImageResource(R.mipmap.blank_search);
            textView.setText("没有找到相关点名");
        } else {
            imageView.setImageResource(R.mipmap.blank_course);
            textView.setText("暂无点名，可点击\"创建课堂\"去点名");
        }

    }

    /**
     * 初始化数据
     */
    private void initView() {
        adapter = new HistoryCallnameAdapter(dao.getClassInfoList(), this);
        listHistoryCallname.setAdapter(adapter);
        listHistoryCallname.enableLoadmore();
        listHistoryCallname.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                PageConst.pageNo = 1;
                if (!searchcontent.getText().toString().trim().equals("")) {
                    //搜索内容时
                    dao.getHistoryClass(PageConst.pageNo, PageConst.pageSize, searchcontent.getText().toString().trim(), CodeConst.EXPAND_GET_HISTORY_CALLNEM_PUSHDOWN);
                } else {
                    dao.getHistoryClass(PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_HISTORY_CALLNEM_PUSHDOWN);
                }
                linearLayoutManager.scrollToPosition(0);
            }
        });
        listHistoryCallname.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
                if (itemsCount > (PageConst.pageSize - 1)) {
                    maxLastPositon = maxLastVisiblePosition;
                    if (!searchcontent.getText().toString().trim().equals("")) {
                        //搜索内容时
                        dao.getHistoryClass(++PageConst.pageNo, PageConst.pageSize, searchcontent.getText().toString().trim(), CodeConst.EXPAND_GET_HISTORY_CALLNEM_PULLUP);
                    } else {
                        dao.getHistoryClass(++PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_HISTORY_CALLNEM_PULLUP);
                    }
                } else {
                    if (listHistoryCallname != null) {
                        adapter.loadNoDataView();
                    }
                    linearLayoutManager.scrollToPosition(maxLastPositon - 1);
                }
            }
        });
        adapter.setmOnItemClickLitener(new HistoryCallnameAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, ClassInfo classInfo, int position) {
                Intent intent = new Intent(HistoryCallNameActivity.this, SignInfoActivity.class);
                intent.putExtra("ktid", classInfo.getKtid());
                intent.putExtra("kcid", classInfo.getKcid());
                intent.putExtra("pzqd", classInfo.getPzqd() + "");
                startActivityForResult(intent, INTENT_SIGNINFO);
                AnimUtil.intentSlidIn(HistoryCallNameActivity.this);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == INTENT_SIGNINFO) {
            //发送请求，获取列表数据
            PageConst.pageNo = 1;
            if (searchcontent.getText().toString().trim().equals("")) {
                dao.getHistoryClass(PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_HISTORY_CALLNEM_PUSHDOWN);//获取数据
            } else {
                dao.getHistoryClass(PageConst.pageNo, PageConst.pageSize, searchcontent.getText().toString().trim(), CodeConst.EXPAND_GET_HISTORY_CALLNEM_PUSHDOWN);
            }
        }
    }

    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.getStatus().equals("0")) {
                switch (requestCode) {
                    case CodeConst.EXPAND_GET_HISTORY_CALLNEM_FRIST:
                        //获取列表数据 首次请求
                        Log.d("status->" + dao.getStatus());
                        initView();
                        if (searchcontent.getText().toString().trim().equals("")) {
                            countLayout.setVisibility(View.VISIBLE);//点名总次数显示
                            count.setText(dao.getCountCallname() + "");//设置点名总次数
                            searchResult.setVisibility(View.GONE);//不显示搜索结果
                        } else {
                            searchResult.setVisibility(View.VISIBLE);//显示搜索结果
                            searchCount.setText(dao.getCountCallname() + "");
                            countLayout.setVisibility(View.GONE);//点名总次数不显示
                        }
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            layout.setVisibility(View.GONE);
                            listHistoryCallname.hideEmptyView();
                        } else {
                            //无数据处理
                            if (searchcontent.getText().toString().trim().equals("")) {
                                //搜索内容为空
                                setBlankView("");
                            } else {
                                setBlankView("search");
                            }
                            listHistoryCallname.showEmptyView();
                            countLayout.setVisibility(View.GONE);//点名总次数不显示
                        }
                        break;
                    case CodeConst.EXPAND_GET_HISTORY_CALLNEM_PUSHDOWN://获取数据 下拉请求  刷新

                        listHistoryCallname.setRefreshing(false);

                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            listHistoryCallname.hideEmptyView();
                            adapter.refresh(dao.getClassInfoList());
                            if (searchcontent.getText().toString().trim().equals("")) {
                                countLayout.setVisibility(View.VISIBLE);//点名总次数显示
                                count.setText(dao.getCountCallname() + "");//设置点名总次数
                                searchResult.setVisibility(View.GONE);//不显示搜索结果
                            } else {
                                searchResult.setVisibility(View.VISIBLE);//显示搜索结果
                                searchCount.setText(dao.getCountCallname() + "");
                                countLayout.setVisibility(View.GONE);//点名总次数不显示
                            }
                            layout.setVisibility(View.GONE);
                            listHistoryCallname.hideEmptyView();
                        } else {
                            //无数据处理
                            adapter.clear();
                            if (searchcontent.getText().toString().trim().equals("")) {
                                setBlankView("");
                            } else {
                                setBlankView("search");
                            }
                            searchResult.setVisibility(View.GONE);//不显示搜索结果
                            countLayout.setVisibility(View.GONE);//点名总次数不显示
                            listHistoryCallname.showEmptyView();
                        }
                        if (dao.getClassInfoList().size() > (PageConst.pageSize - 1)) {
                            adapter.loadMoreDataView();
                        } else {
                            //数据小于当前页的话则不显示加载更多
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                            linearLayoutManager.scrollToPosition(maxLastPositon);
                        }
                        break;
                    case CodeConst.EXPAND_GET_HISTORY_CALLNEM_PULLUP://获取数据  上拉请求  加载更多
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            adapter.loadmore(dao.getClassInfoList());
                        } else {
                            //无数据则不显示下一页
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;
                }
            } else {
                MessageUtils.showImageShortToast(this, dao.getStatusCode());
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(this, "请求数据异常");
        }
    }

    /**
     * 点击搜索按钮
     */
    @OnClick(R.id.searchBtn)
    void onClick() {
        //去搜索
        if (!searchcontent.getText().toString().trim().equals("")) {
            //发送请求，获取列表数据
            PageConst.pageNo = 1;
            dao.getHistoryClass(PageConst.pageNo, PageConst.pageSize, searchcontent.getText().toString().trim(), CodeConst.EXPAND_GET_HISTORY_CALLNEM_PUSHDOWN);//获取数据
            //隐藏软键盘
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchcontent.getWindowToken(), 0);
        }
    }

    /**
     * 关闭搜索区域
     */
    @OnClick(R.id.close_search)
    void closeSearchContainer() {
        searchResult.setVisibility(View.GONE);
    }

    @Override
    public String setupToolBarTitle() {
        return "历史点名";
    }

    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    @OnClick(R.id.toolbar_leftbtn)
    void onToolbarLeftClick() {
        finish();
    }
}
